#coding=utf-8
from indexdb import get_dbconnector

class Price(object):

    def __init__(self, queryset):
        
        self.date = queryset[2]
        
        self.start = queryset[3]
        self.end = queryset[4]
        self.high = queryset[5]
        self.low = queryset[6]
        
        self.volume = queryset[7]
        self.amount = queryset[8]
        self.fluctuation = queryset[9]
        self.change = queryset[10]
                
class Index(object):
                
    def __init__(self, con, name='szzs'):
        self.con = con
        self.name = name
        
    def price_on(self, exdate):
        c = self.con.cursor()
        c.execute('select * from stock_index where name=? and date=?', 
                 (self.name, exdate))
        r = c.fetchone()
        if not r:return None
        return Price(r)
        
    def price_after(self, exdate, n=1):
        c = self.con.cursor()
        c.execute('select * from stock_index where name=? and date>?  order by date limit ? ',
                 (self.name, exdate, n))
        r = c.fetchall()
        if not r:return None
        if n == 1:
            return Price(r[0])
        else:
            ps = []
            for d in r:
                ps.append(Price(d))
            return ps
                
    def price_before(self, exdate, n=1):
        c = self.con.cursor()
        c.execute('select * from stock_index where name=? and date<? order by date desc limit ?',
                 (self.name, exdate, n))
                 
        r = c.fetchall()
        if not r:return None
        if n == 1:
            return Price(r[0])
        else:
            ps = []
            for d in r:
                ps.append(Price(d))
            return ps
            
    def ap_on(self, exdate, n=5):
        ps = self.price_before(exdate, n)
        if not ps or len(ps) != n:
            return None
        es = [p.end for p in ps]
        return sum(es)/n
        
    def av_on(self, exdate, n=5):
        ps = self.price_before(exdate, n)
        if not ps or len(ps) != n:
            return None
        vs = [p.volume for p in ps]
        return sum(vs)/float(n)